const fs = require("fs")
const path = require("path")
const readline = require('readline');
const { execSync } = require('child_process');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

//文件绝对路径
const pathcomponent = path.join(__dirname + '/path.js')

//正则匹配配置，以及路径前缀
const pathMap = {
  taxes: ['票税配置---勿动', '/taxes'],
  fund: ['资金配置---勿动', ''],
  collect: ['应收账款配置---勿动', '/collect'],
  account: ['会计配置---勿动', '/account'],
  monthSettle: ['账务配置---勿动', '/monthSettle'],
  siteFinance: ['网点金融配置---勿动', '/siteFinance'],
}

//默认必填
function getUserInput(question, must = true) {
  return new Promise((resolve) => {
    const ask = () => {
      rl.question(question, (input) => {
        input = input.trim(); //去除左右空格
        if (input.includes(' ') && must) {
          console.log('输入不能为空，或包含空格，请重新输入。');
          ask();  // 用户输入为空，重新询问
        } else {
          resolve(input.trim());
        }
      });
    };
    ask();
  });
}


async function main() {
  let category
  // 获取用户输入，直到输入合法
  while (true) {
    category = await getUserInput('taxes 票税| fund 资金 | collect 应收账款 | account 会计 ｜ monthSettle 帐务 ｜ siteFinance网点金融  请输入类别:');

    if (pathMap[category] && pathMap[category][0]) {
      break;  // 输入合法，跳出循环
    } else {
      console.log('类别错误，请重新输入');
    }
  }
  const component = await getUserInput('请输组件 ：');
  const label = await getUserInput('选填注释? ：', false);
  // 提示用户输入
  try {
    const fileData = fs.readFileSync(pathcomponent, 'utf-8')
    //查看当前匹配到的数据在第几行
    const line = fileData.split('\n').findIndex((line) => line.includes(pathMap[category][0]));
    //然后打印匹配到的这一行的上一行代码
    const productUrl = `"${pathMap[category][1]}/${component}",  ${label.trim() === "" ? '' : '//'} ${label}`
    const dynamicRegex = new RegExp(`\\/\\*\\s*${pathMap[category][0]}\\s*\\*\\/`);
    const newData = fileData.replace(dynamicRegex, `${component}:${productUrl} \r\/\* ${pathMap[category][0]} \*\/`
    )
    console.log('打印生成局部代码');
    console.log(fileData.split('\n')[line - 2])
    console.log(fileData.split('\n')[line - 1])
    console.warn(`${component}:${productUrl} 新增path`);
    console.log(fileData.split('\n')[line + 1])
    fs.writeFileSync(pathcomponent, newData, 'utf-8')
    // 使用 prettier 命令行工具格式化文件
    execSync(`npx prettier --write ${pathcomponent}`);
    rl.close();
  } catch (error) {

  }
}

main()




